<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useTemplateStore } from '@/stores/template';
// 导入Element Plus的消息组件
import { ElMessage, ElMessageBox } from 'element-plus';

const router = useRouter();
const userStore = useUserStore();
const templateStore = useTemplateStore();

// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const totalPages = computed(() => Math.ceil(templateStore.totalTemplates / pageSize.value));

// 搜索参数
const searchQuery = ref('');

// 分类过滤
const categories = ref([]);
const selectedCategory = ref('');

// 加载状态
const loading = ref(false);

// 获取模板列表
const fetchTemplates = async () => {
  loading.value = true;
  try {
    await templateStore.fetchTemplates(currentPage.value, pageSize.value, selectedCategory.value || null);
    // 提取所有分类
    const uniqueCategories = new Set();
    templateStore.templates.forEach(template => {
      if (template.category) {
        uniqueCategories.add(template.category);
      }
    });
    categories.value = Array.from(uniqueCategories);
  } catch (error) {
    console.error('Failed to fetch templates:', error);
  } finally {
    loading.value = false;
  }
};

// 创建新模板
const createNewTemplate = () => {
  router.push('/templates/create');
};

// 查看模板详情
const viewTemplate = (templateId) => {
  router.push(`/templates/${templateId}`);
};

// 使用模板创建文档
const createDocumentFromTemplate = (templateId, event) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();
  router.push(`/documents/create?templateId=${templateId}`);
};

// 删除模板
const deleteTemplate = async (templateId, event) => {
  // 阻止事件冒泡，避免触发卡片点击事件
  event.stopPropagation();
  
  // 使用Element Plus的MessageBox进行确认操作
  ElMessageBox.confirm(
    '确定要删除这个模板吗？此操作不可撤销。',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      // 用户点击确认，执行删除操作
      loading.value = true;
      try {
        const success = await templateStore.deleteTemplate(templateId);
        if (success) {
          // 刷新模板列表
          await fetchTemplates();
          // 显示成功消息
          ElMessage({
            type: 'success',
            message: '模板删除成功'
          });
        }
      } catch (error) {
        console.error('Failed to delete template:', error);
        // 显示错误消息
        ElMessage({
          type: 'error',
          message: '删除模板失败'
        });
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消操作
      ElMessage({
        type: 'info',
        message: '已取消删除'
      });
    });
};

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchTemplates();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  fetchTemplates();
};

// 处理分类过滤
const handleCategoryChange = () => {
  currentPage.value = 1; // 重置到第一页
  fetchTemplates();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchTemplates();
});
</script>

<template>
  <div class="template-list-container">
    <div class="template-list-header">
      <h1 class="page-title">文档模板</h1>
      <button v-if="userStore.isAdmin" @click="createNewTemplate" class="create-template-btn">
        <span class="icon">+</span> 新建模板
      </button>
    </div>

    <div class="template-list-filters">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索模板..."
          @keyup.enter="handleSearch"
        />
        <button @click="handleSearch" class="search-btn">搜索</button>
      </div>

      <div class="category-filter">
        <label for="category">分类：</label>
        <select id="category" v-model="selectedCategory" @change="handleCategoryChange">
          <option value="">全部</option>
          <option v-for="category in categories" :key="category" :value="category">
            {{ category }}
          </option>
        </select>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-placeholder">
      <p>加载中...</p>
    </div>

    <!-- 空状态 -->
    <div v-else-if="templateStore.templates.length === 0" class="empty-state">
      <p>暂无模板</p>
      <button v-if="userStore.isAdmin" @click="createNewTemplate" class="btn-primary">创建第一个模板</button>
    </div>

    <!-- 模板列表 -->
    <div v-else class="templates-grid">
      <div 
        v-for="template in templateStore.templates" 
        :key="template.id" 
        class="template-card"
        @click="viewTemplate(template.id)"
      >
        <div class="template-card-content">
          <h3 class="template-title">{{ template.name }}</h3>
          <p class="template-category">{{ template.category }}</p>
        </div>
        <div class="template-card-footer">
          <button 
            class="use-template-btn" 
            @click="createDocumentFromTemplate(template.id, $event)"
          >
            使用此模板
          </button>
          <button 
            v-if="userStore.isAdmin || template.userId === userStore.currentUser?.id" 
            class="delete-btn" 
            @click="deleteTemplate(template.id, $event)"
            title="删除模板"
          >
            删除
          </button>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="templateStore.templates.length > 0" class="pagination">
      <button 
        :disabled="currentPage === 1" 
        @click="handlePageChange(currentPage - 1)"
        class="pagination-btn"
      >
        上一页
      </button>
      
      <span class="pagination-info">{{ currentPage }} / {{ totalPages }}</span>
      
      <button 
        :disabled="currentPage === totalPages" 
        @click="handlePageChange(currentPage + 1)"
        class="pagination-btn"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<style scoped>
.template-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2.5rem 1.5rem;
  background-color: #f9fafb;
  min-height: 100vh;
}

.template-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.5rem;
  background-color: white;
  padding: 1.5rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 2rem;
  font-weight: 700;
  color: #111827;
  margin: 0;
  position: relative;
  padding-left: 1rem;
}

.page-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0.25rem;
  bottom: 0.25rem;
  width: 4px;
  background-color: #4f46e5;
  border-radius: 2px;
}

.create-template-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.75rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.create-template-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.1);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.create-template-btn:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.create-template-btn:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}

.create-template-btn .icon {
  font-size: 1.25rem;
  font-weight: 600;
  line-height: 1;
  margin-right: 0.25rem;
}

.template-list-filters {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  background-color: white;
  padding: 1.25rem 2rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  flex-wrap: wrap;
  gap: 1rem;
}

.search-box {
  display: flex;
  gap: 0.75rem;
  flex: 1;
  max-width: 400px;
  position: relative;
}

.search-box input {
  flex: 1;
  padding: 0.875rem 1rem 0.875rem 2.5rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 1rem;
  background-color: #f9fafb;
  transition: all 0.3s ease;
}

.search-box::before {
  content: '🔍';
  position: absolute;
  left: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #9ca3af;
  font-size: 1rem;
  pointer-events: none;
}

.search-box input:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
  background-color: white;
}

.search-btn {
  padding: 0.875rem 1.25rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(79, 70, 229, 0.2);
}

.search-btn:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(79, 70, 229, 0.3);
}

.category-filter {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.category-filter label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
}

.category-filter select {
  padding: 0.75rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.875rem;
  background-color: #f9fafb;
  min-width: 150px;
  transition: all 0.3s ease;
  cursor: pointer;
  color: #4b5563;
}

.category-filter select:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.15);
  background-color: white;
  color: #111827;
}

.category-filter select:hover {
  border-color: #9ca3af;
}

/* 模板卡片样式 */
.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.75rem;
  margin-bottom: 2.5rem;
}

.template-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 200px;
  display: flex;
  flex-direction: column;
  position: relative;
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.template-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(79, 70, 229, 0) 0%, rgba(79, 70, 229, 0.02) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
  z-index: 1;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.08);
  border-color: rgba(79, 70, 229, 0.2);
}

.template-card:hover::after {
  opacity: 1;
}

.template-card-content {
  padding: 1.75rem 1.75rem 0.25rem 1.75rem;
  flex: 1;
  position: relative;
  z-index: 2;
}

.template-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #111827;
  margin-bottom: 0.75rem;
  /* 文本溢出省略 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: color 0.3s ease;
}

.template-card:hover .template-title {
  color: #4f46e5;
}

.template-category {
  font-size: 0.875rem;
  color: #6b7280;
  margin-bottom: 0.75rem;
  display: inline-block;
  padding: 0.25rem 0.75rem;
  background-color: #f3f4f6;
  border-radius: 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.template-card:hover .template-category {
  background-color: rgba(79, 70, 229, 0.1);
  color: #4f46e5;
}

.template-card-footer {
  padding: 1.25rem 1.75rem;
  border-top: 1px solid #e5e7eb;
  background-color: #f9fafb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  z-index: 2;
  transition: background-color 0.3s ease;
}

.template-card:hover .template-card-footer {
  background-color: #f3f4f6;
}

.use-template-btn {
  padding: 0.625rem 1.25rem;
  background-color: transparent;
  border: 1px solid #4f46e5;
  color: #4f46e5;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.use-template-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #4f46e5;
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.use-template-btn:hover {
  color: white;
  border-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(79, 70, 229, 0.2);
}

.use-template-btn:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}

.delete-btn {
  padding: 0.375rem 0.75rem;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.75rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 5px rgba(239, 68, 68, 0.2);
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.delete-btn::before {
  content: '🗑️';
  font-size: 0.875rem;
}

.delete-btn:hover {
  background-color: #dc2626;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(239, 68, 68, 0.3);
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1.5rem;
  margin-top: 2.5rem;
  background-color: white;
  padding: 1rem;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  max-width: 400px;
  margin-left: auto;
  margin-right: auto;
}

.pagination-btn {
  padding: 0.625rem 1.25rem;
  background-color: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #4b5563;
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f3f4f6;
  border-color: #9ca3af;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  color: #111827;
}

.pagination-btn:disabled {
  opacity: 0.4;
  cursor: not-allowed;
}

.pagination-info {
  font-size: 0.875rem;
  font-weight: 500;
  color: #4b5563;
  background-color: #f3f4f6;
  padding: 0.5rem 1rem;
  border-radius: 6px;
}

/* 加载和空状态样式 */
.loading-placeholder,
.empty-state {
  padding: 4rem 2rem;
  text-align: center;
  color: #6b7280;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin: 2rem 0;
}

.empty-state p {
  margin-bottom: 1.5rem;
  font-size: 1.125rem;
  color: #4b5563;
}

.btn-primary {
  display: inline-block;
  padding: 0.75rem 1.75rem;
  background-color: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.1);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.btn-primary:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.btn-primary:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}
</style>